﻿#if !UNITY_IOS || HUpdate
using UnityModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

class DownloadWatcher
{
    bool isStart = false;
    System.Diagnostics.Stopwatch watcher = new System.Diagnostics.Stopwatch();
    bool pingreport = false;
    //下载速度2秒刷新一次
    public void Start() {
        if (isStart)
            return;
        isStart = true;
        pingreport = false;
        //Debug.Log("watcher start");
        DownloadSpeedHelper.GetSpeed += DownloadSpeedHelper_GetSpeed;
    }
    Ping ping;
    System.Diagnostics.Stopwatch pingtimeout = new System.Diagnostics.Stopwatch();
    void WaitPingDone() {
        if (ping != null && ping.isDone)
        {
            pingtimeout.Stop();
            //WebStepsMonitorHelper.SendStepsMonitor((int)Monitor.ReportId.CDNPing, ping.ip + "***" + ping.time + "ms");
            ping.DestroyPing();
            ping = null;
            CreatePing();
        } else if (pingtimeout.Elapsed.TotalSeconds>10) {
            //WebStepsMonitorHelper.SendStepsMonitor((int)Monitor.ReportId.CDNPing, ping.ip + "***fail");
            ping.DestroyPing();
            ping = null;
            CreatePing();
        }
    }

    void CreatePing() {
        if (pingQueue.Count > 0) {
            ping = new Ping(pingQueue.Dequeue());
            pingtimeout.Reset();
            pingtimeout.Start();
        }
    }
    Queue<string> pingQueue = new Queue<string>();
    void DoPingTest() {
        if (!pingreport&&ping == null) {
            pingreport = true;
            Uri uri = new Uri(UpdateSettings.Instance.CdnUrl);
            IPAddress[] add = Dns.GetHostEntry(uri.Host).AddressList;
            for (int i = 0; i < add.Length; i++) {
                if (add[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
                    string ipadd = add[i].ToString();
                    if(!pingQueue.Contains(ipadd))
                        pingQueue.Enqueue(ipadd);
                    
                }
            }
            CreatePing();
        }
    }


    
    private void DownloadSpeedHelper_GetSpeed(double speedK)
    {
        // Debug.Log("DownloadTask RunningTaskNum:"+ DownloadTask.RunningTaskNum);
       
        if (!DownloadComponent.Instance.IsPreDownloadFinished)
        {
            if (DownloadMonitor.Enable == true)
            {
                WaitPingDone();
                if (speedK < 512)
                {
                    if (!watcher.IsRunning)
                    {
                        watcher.Reset();
                        watcher.Start();
                    }
                    else if (watcher.ElapsedMilliseconds > 30000)
                    {
                        //WebStepsMonitorHelper.SendStepsMonitor((int)Monitor.ReportId.DownloadSpeed, speedK + "Kb");
                        DoPingTest();
                        watcher.Restart();
                    }
                }
                else
                {
                    watcher.Stop();
                }
            }

            if (speedK < 4096)
            {
                if (DownloadClientConfig.HighTaskMaxRunningCount < DownloadClientConfig.HighTaskMaxCount)
                {

                    DownloadClientConfig.HighTaskMaxRunningCount++;
                    Debug.Log("upgrade high thread count:" + DownloadClientConfig.HighTaskMaxRunningCount);
                }
            }
            else if (speedK > 8192) {
                if (DownloadClientConfig.HighTaskMaxRunningCount>0)
                {

                    DownloadClientConfig.HighTaskMaxRunningCount--;
                    Debug.Log("downgrade high thread count:" + DownloadClientConfig.HighTaskMaxRunningCount);
                }
            }
        }
        else {
            if (speedK < 512)
            {
                if (DownloadClientConfig.LowTaskMaxRunningCount < DownloadClientConfig.LowTaskMaxCount)
                {
                    DownloadClientConfig.LowTaskMaxRunningCount++;
                    Debug.Log("upgrade low thread count:" + DownloadClientConfig.LowTaskMaxRunningCount);
                }
            }
        }
        
    }

    public void Stop() {
        isStart = false;
        if (ping != null) {
            ping.DestroyPing();
            ping = null;
        }
        pingtimeout.Stop();
        Debug.Log("watcher stop");
        DownloadSpeedHelper.GetSpeed -= DownloadSpeedHelper_GetSpeed;
       
    }
}

#endif